package com.rainbow.gwt.accounting.server.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil{
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	@SuppressWarnings("rawtypes")
	private static final ThreadLocal threadLocal = new ThreadLocal();
	private static final Configuration cfg = new Configuration();
	private static SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	public static Session currentSession() throws HibernateException{
		Session session = (Session) threadLocal.get();
		if(session == null){
			try{
				if(sessionFactory == null){
					cfg.configure(CONFIG_FILE_LOCATION);
					sessionFactory = cfg.buildSessionFactory();
				}
			}catch(Exception e){
				System.out.println("%%%% Error Creating SessionFactory %%%%");
				e.printStackTrace();
			}
			session = sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}
	
	@SuppressWarnings("unchecked")
	public static void closeSession() throws HibernateException{
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if(session != null){
			session.close();
		}
	}
}
